import os
import csscompressor
import jsmin
import htmlmin


def compress_files(dir_path):
    for root, dirs, files in os.walk(dir_path):  # 遍历所有文件和目录
        for file in files:
            input_path = os.path.join(root, file)
            file_ext = os.path.splitext(file)[-1]  # 获取文件扩展名
            if file_ext in ('.css', '.js', '.html', '.htm'):
                with open(input_path, 'r+', encoding='utf-8') as f_in:
                    content = f_in.read()
                    f_in.seek(0)  # 重新设置文件指针到开头
                    f_in.truncate()  # 清空文件内容

                    if file_ext == '.css':
                        compressed_content = csscompressor.compress(content)
                    elif file_ext == '.js':
                        compressed_content = jsmin.jsmin(content)
                    else:
                        compressed_content = htmlmin.minify(content)

                    f_in.write(compressed_content)